package com.example.qrwebsocketdemo.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.example.qrwebsocketdemo.pojo.UserToken;
import com.example.qrwebsocketdemo.repository.UserTokenRepository;
import com.example.qrwebsocketdemo.service.UserTokenService;
import com.example.qrwebsocketdemo.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserTokenServiceImpl implements UserTokenService {

    @Autowired
    private UserTokenRepository userRepository;

    @Override
    public String createQrImg() {
        //生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
        String uuid = IdUtil.simpleUUID();
        UserToken userToken = userRepository.save(new UserToken(uuid, null, new Date(), null, "1"));
        return userToken.getUuid();
    }

    @Override
    public void bindUserIdAndToken(Integer userId, String token, Integer projId) {
        //模拟查是否存在该用户
        UserToken userToken = userRepository.getByUuid(token);
        if (userToken == null) {
            JSONObject jsonObject = setProperties(400, "错误的请求！", userId, projId);
            WebSocketServer.sendInfo(jsonObject.toStringPretty(), token);
            return;
        }
        //校验二维码是否过期
        Date createDate = new Date(userToken.getCreateTime().getTime() + (1000 * 60 * 2));
        Date nowDate = new Date();
        if (nowDate.getTime() > createDate.getTime()) { //当前时间大于校验时间-二维码过期
            JSONObject jsonObject = setProperties(500, "二维码失效！", userId, projId);
            WebSocketServer.sendInfo(jsonObject.toStringPretty(), token);
            return;
        }
        //更新状态为启用
        userToken.setLoginTime(new Date());
        userToken.setUserId(userId);
        userToken.setState("0");
        UserToken user = userRepository.save(userToken);
        if (user.getState().equals("1")) {
            JSONObject jsonObject = setProperties(500, "用户未启用！", userId, projId);
            WebSocketServer.sendInfo(jsonObject.toStringPretty(), token);
            return;
        }
        JSONObject jsonObject = setProperties(200, "登录成功！", userId, projId);
        WebSocketServer.sendInfo(jsonObject.toStringPretty(), token);
    }

    private JSONObject setProperties(Integer code, String msg, Integer userId, Integer projId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("code", code);
        jsonObject.set("msg", msg);
        jsonObject.set("userId", userId);
        if (projId != null)
            jsonObject.set("projId", projId);
        return jsonObject;
    }

}
